Remove leading zeros from an IP address¶
Remove leading zeros from an IP address.
Method: Traversal and join
The approach is to split the given string by “.” and then convert it to an integer
which removes the leading zeros and then join back them to a string.
To convert a string to an integer we can use int(s) and then convert it back
to string by str(s) and then join them back by using join function.
def remove_lead_zeros(ip):
# splits the IP by "."
# converts the words to integeres to remove leading zeros
# convert back the integer to string and join them back to a IP string
new_ip = ".".join([str(int(token)) for token in ip.split(".")])
return new_ip
# test
print(remove_lead_zeros("100.020.003.400")) # 100.20.3.400
print(remove_lead_zeros("001.200.001.004")) # 1.200.001.004